package top.birdhk.TestAPI.processfunction;

import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;
import top.birdhk.TestAPI.beans.SensorReading;
import top.birdhk.TestAPI.state.StateTest_KeyedStateApplicationCase;

public class ProcessTest_KeyedProcessFunction {


    public static void main(String[] args) throws Exception{



        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();


        env.setParallelism(1);

//        DataStreamSource<String> dataStream = env.readTextFile("E:\\flink\\wordcount\\src\\main\\resources\\sensor.txt");

        DataStreamSource<String> dataStream = env.socketTextStream("localhost", 7777);


        SingleOutputStreamOperator<SensorReading> inputStream = dataStream.map(line -> {
            String[] split = line.split(",");
            return new SensorReading(split[0], new Long(split[1]), new Double(split[2]));
        });


        // 测试keyedprocessFunction，先分组然后自定义处理
        inputStream.keyBy("id")
                .process(new MyProcess())
                .print();


        env.execute();



    }

    public static  class MyProcess extends  KeyedProcessFunction<Tuple,SensorReading,Integer>{


        ValueState<Long> tsTimeState;

        public MyProcess() {
        }

        @Override
        public void open(Configuration parameters) throws Exception {
            tsTimeState = getRuntimeContext().getState(new ValueStateDescriptor<Long>("ts-timer",Long.class));
        }

        @Override
        public void processElement(SensorReading sensorReading, Context context, Collector<Integer> collector) throws Exception {
            collector.collect(sensorReading.getId().length());
            context.timestamp();
            context.getCurrentKey();

            // 处理时间
            long l = context.timerService().currentProcessingTime();
            // watermark(事件时间)
            context.timerService().currentWatermark();
            //注册定时器，参数是触发时间戳
            context.timerService().registerProcessingTimeTimer(l + 1000L);
            tsTimeState.update(l + 1000L);
            //context.timerService().registerEventTimeTimer((sensorReading.getTimestamp() + 10) * 1000);
            //删除定时器
            context.timerService().deleteEventTimeTimer(tsTimeState.value());
        }

        /**
         * 定时器执行方法
         * @param timestamp
         * @param ctx
         * @param out
         * @throws Exception
         */
        @Override
        public void onTimer(long timestamp, OnTimerContext ctx, Collector<Integer> out) throws Exception {
            System.out.println(timestamp+"定时器触发");
        }


        @Override
        public void close() throws Exception {
            tsTimeState.clear();
        }


    }





}
